/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#ifndef __CPU_EDGE_LSQ_UNIT_HH__
#define __CPU_EDGE_LSQ_UNIT_HH__

#include <algorithm>
#include <cstring>
#include <map>
#include <queue>

#include "arch/faults.hh"
#include "arch/locked_mem.hh"
#include "config/full_system.hh"
#include "config/the_isa.hh"
#include "base/fast_alloc.hh"
#include "base/hashmap.hh"
#include "cpu/inst_seq.hh"
#include "mem/packet.hh"
#include "mem/port.hh"

class DerivEdgeCPUParams;

template <class Impl>
class EdgeLSQUnit {
  protected:
    typedef TheISA::IntReg IntReg;
  public:
    typedef typename Impl::CPU CPU;
    typedef typename Impl::DynInstPtr DynInstPtr;
    typedef typename Impl::EdgeBlockPtr BlockPtr;
    typedef typename Impl::CPUPol::Execute Execute;
    typedef typename Impl::CPUPol::LSQ LSQ;
    typedef typename Impl::CPUPol::Issue2Execute Issue2Execute;

    typedef TheISA::BlockID BlockID;

  public:
    /** Constructs an LSQ unit. init() must be called prior to use. */
    EdgeLSQUnit();

    /** Initializes the LSQ unit with the specified number of entries. */
    void init(CPU *cpu_ptr, Execute *execute_ptr, DerivEdgeCPUParams *params,
            LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
            unsigned id);

    /** Returns the name of the LSQ unit. */
    std::string name() const;

    /** Registers statistics. */
    void regStats();

    /** Sets the pointer to the dcache port. */
    void setDcachePort(Port *dcache_port);

    /** Switches out LSQ unit. */
    void switchOut();

    /** Takes over from another CPU's thread. */
    void takeOverFrom();

    /** Returns if the LSQ is switched out. */
    bool isSwitchedOut() { return switchedOut; }

    /** Ticks the LSQ unit, which in this case only resets the number of
     * used cache ports.
     * @todo: Move the number of used ports up to the LSQ level so it can
     * be shared by all LSQ units.
     */
    void tick() { usedPorts = 0; }

    /** Inserts an instruction. */
    void insert(DynInstPtr &inst);
    /** Inserts a load instruction. */
    void insertLoad(DynInstPtr &load_inst);
    /** Inserts a store instruction. */
    void insertStore(DynInstPtr &store_inst);

    /** Executes a load instruction. */
    Fault executeLoad(DynInstPtr &inst);

    Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
    /** Executes a store instruction. */
    Fault executeStore(DynInstPtr &inst);

    /** Nullify a store instruction. */
    void nullifyStore(DynInstPtr &inst);

    /** Commits the inst block. */
    void commitInstBlock(BlockID blockID);

    /** Commits the head load. */
    void commitLoad();

    /** Commits loads older than a specific sequence number. */
    void commitLoads(BlockID blockID);

    /** Commits stores older than a specific sequence number. */
    void commitStores(BlockID blockID);

    /** Writes back stores. */
    void writebackStores();

    /** Completes the data access that has been returned from the
     * memory system. */
    void completeDataAccess(PacketPtr pkt);

    /** Clears all the entries in the LQ. */
    void clearLQ();

    /** Clears all the entries in the SQ. */
    void clearSQ();

    /** Resizes the LQ to a given size. */
    void resizeLQ(unsigned size);

    /** Resizes the SQ to a given size. */
    void resizeSQ(unsigned size);

    void setStoreMask(BlockPtr inst_block)
    { smask = inst_block ->getStoreMask();}

    /** Squashes all instructions younger than a specific sequence number. */
    void squash(const TheISA::BlockID &squashed_num);

    /** Returns if there is a memory ordering violation. Value is reset upon
     * call to getMemDepViolator().
     */
    bool violation() { return memDepViolator; }

    /** Returns the memory ordering violator. */
    DynInstPtr getMemDepViolator();

    /** Returns if a load became blocked due to the memory system. */
    bool loadBlocked()
    { return isLoadBlocked; }

    /** Clears the signal that a load became blocked. */
    void clearLoadBlocked()
    { isLoadBlocked = false; }

    /** Returns if the blocked load was handled. */
    bool isLoadBlockedHandled()
    { return loadBlockedHandled; }

    /** Records the blocked load as being handled. */
    void setLoadBlockedHandled()
    { loadBlockedHandled = true; }

    /** Returns the number of free entries (min of free LQ and SQ entries). */
    unsigned numFreeEntries();

    /** Returns the number of loads ready to execute. */
    int numLoadsReady();

    /** Returns the number of loads in the LQ. */
    int numLoads() { return loads; }

    /** Returns the number of stores in the SQ. */
    int numStores() { return stores; }

    /** Returns if either the LQ or SQ is full. */
    bool isFull() { return lqFull() || sqFull(); }

    /** Returns if the LQ is full. */
    bool lqFull() { return loads >= (LQEntries - 1); }

    /** Returns if the SQ is full. */
    bool sqFull() { return stores >= (SQEntries - 1); }

    /** Returns the number of instructions in the LSQ. */
    unsigned getCount() { return loads + stores; }

    /** Returns if there are any stores to writeback. */
    bool hasStoresToWB() { return storesToWB; }

    /** Returns the number of stores to writeback. */
    int numStoresToWB() { return storesToWB; }

    /** Returns if the LSQ unit will writeback on this cycle. */
    bool willWB() { return storeQueue[storeWBIdx].canWB &&
                        !storeQueue[storeWBIdx].completed &&
                        !isStoreBlocked; }

    /** Handles doing the retry. */
    void recvRetry();

  private:
    /** Writes back the instruction, sending it to IEW. */
    void writeback(DynInstPtr &inst, PacketPtr pkt);

    /** Handles completing the send of a store to memory. */
    void storePostSend(PacketPtr pkt);

    /** Completes the store at the specified index. */
    void completeStore(int store_idx);

    /** Increments the given store index (circular queue). */
    inline void incrStIdx(int &store_idx)
    {
        if (++store_idx >= SQEntries)
            store_idx = 0;
    }
    /** Decrements the given store index (circular queue). */
    inline void decrStIdx(int &store_idx)
    {
        if (--store_idx < 0)
        store_idx += SQEntries;
    }
    /** Increments the given load index (circular queue). */
    inline void incrLdIdx(int &load_idx)
    {
        if (++load_idx >= LQEntries)
            load_idx = 0;
    }
    /** Decrements the given load index (circular queue). */
    inline void decrLdIdx(int &load_idx)
    {
        if (--load_idx < 0)
            load_idx += LQEntries;
    }

  public:
    /** Debugging function to dump instructions in the LSQ. */
    void dumpInsts();

  private:
    /** Pointer to the CPU. */
    CPU *cpu;

    /** Pointer to the IEW stage. */
    Execute *executeStage;

    /** Pointer to the LSQ. */
    LSQ *lsq;

    /** Pointer to the dcache port.  Used only for sending. */
    Port *dcachePort;

    /** Derived class to hold any sender state the LSQ needs. */
    class LSQSenderState : public Packet::SenderState, public FastAlloc
    {
      public:
        /** Default constructor. */
        LSQSenderState()
            : noWB(false)
        { }

        /** Instruction who initiated the access to memory. */
        DynInstPtr inst;
        /** Whether or not it is a load. */
        bool isLoad;
        /** The LQ/SQ index of the instruction. */
        int idx;
        /** Whether or not the instruction will need to writeback. */
        bool noWB;
    };

    /** Writeback event, specifically for when stores forward data to loads. */
    class WritebackEvent : public Event {
      public:
        /** Constructs a writeback event. */
        WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, EdgeLSQUnit *lsq_ptr);

        /** Processes the writeback event. */
        void process();

        /** Returns the description of this event. */
        const char *description() const;

      private:
        /** Instruction whose results are being written back. */
        DynInstPtr inst;

        /** The packet that would have been sent to memory. */
        PacketPtr pkt;

        /** The pointer to the LSQ unit that issued the store. */
        EdgeLSQUnit<Impl> *lsqPtr;
    };

  public:
    struct SQEntry {
        /** Constructs an empty store queue entry. */
        SQEntry()
            : inst(NULL), req(NULL), size(0),
              canWB(0), committed(0), completed(0), nullified(0)
        {
            std::memset(data, 0, sizeof(data));
        }

        /** Constructs a store queue entry for a given instruction. */
        SQEntry(DynInstPtr &_inst)
            : inst(_inst), req(NULL), size(0),
              canWB(0), committed(0), completed(0), nullified(0)
        {
            std::memset(data, 0, sizeof(data));
        }

        /** The store instruction. */
        DynInstPtr inst;
        /** The request for the store. */
        RequestPtr req;
        /** The size of the store. */
        int size;
        /** The store data. */
        char data[sizeof(IntReg)];
        /** Whether or not the store can writeback. */
        bool canWB;
        /** Whether or not the store is committed. */
        bool committed;
        /** Whether or not the store is completed. */
        bool completed;
    /** Whether or not the store is nullified. */
    bool nullified;
    };

  private:
    /** The EdgeLSQUnit thread id. */
    ThreadID lsqID;

    /** The store queue. */
    std::vector<SQEntry> storeQueue;

    /** The load queue. */
    std::vector<DynInstPtr> loadQueue;

    /** The number of LQ entries, plus a sentinel entry (circular queue).
     *  @todo: Consider having var that records the true number of LQ entries.
     */
    unsigned LQEntries;
    /** The number of SQ entries, plus a sentinel entry (circular queue).
     *  @todo: Consider having var that records the true number of SQ entries.
     */
    unsigned SQEntries;

    /** The number of load instructions in the LQ. */
    int loads;
    /** The number of store instructions in the SQ. */
    int stores;
    /** The number of store instructions in the SQ waiting to writeback. */
    int storesToWB;

    /** The index of the head instruction in the LQ. */
    int loadHead;
    /** The index of the tail instruction in the LQ. */
    int loadTail;

    /** The index of the head instruction in the SQ. */
    int storeHead;
    /** The index of the first instruction that may be ready to be
     * written back, and has not yet been written back.
     */
    int storeWBIdx;
    /** The index of the tail instruction in the SQ. */
    int storeTail;

    uint32_t smask;
    /// @todo Consider moving to a more advanced model with write vs read ports
    /** The number of cache ports available each cycle. */
    int cachePorts;

    /** The number of used cache ports in this cycle. */
    int usedPorts;

    /** Is the LSQ switched out. */
    bool switchedOut;

    //list<InstSeqNum> mshrSeqNums;

    /** Wire to read information from the issue stage time queue. */
    typename TimeBuffer<Issue2Execute>::wire fromIssue;

    /** Whether or not the LSQ is stalled. */
    bool stalled;
    /** The store that causes the stall due to partial store to load
     * forwarding.
     */
    InstSeqNum stallingStoreIsn;
    /** The index of the above store. */
    int stallingLoadIdx;

    /** The packet that needs to be retried. */
    PacketPtr retryPkt;

    /** Whehter or not a store is blocked due to the memory system. */
    bool isStoreBlocked;

    /** Whether or not a load is blocked due to the memory system. */
    bool isLoadBlocked;

    /** Has the blocked load been handled. */
    bool loadBlockedHandled;

    /** The sequence number of the blocked load. */
    InstSeqNum blockedLoadSeqNum;

    /** The oldest load that caused a memory ordering violation. */
    DynInstPtr memDepViolator;

    // Will also need how many read/write ports the Dcache has.  Or keep track
    // of that in stage that is one level up, and only call executeLoad/Store
    // the appropriate number of times.
    /** Total number of loads that all data forwarded from LSQ stores. */
    Stats::Scalar lsqAllForwLoads;

    /** Total number of loads that partial data forwarded from LSQ stores. */
    Stats::Scalar lsqPartialForwLoads;

    /** Total number of squashed loads. */
    Stats::Scalar lsqSquashedLoads;

    /** Total number of responses from the memory system that are
     * ignored due to the instruction already being squashed or block completed.  */
    Stats::Scalar lsqIgnoredResponses;

    /** Total number of squashed stores. */
    Stats::Scalar lsqSquashedStores;

    /** Number of loads that were rescheduled. */
    Stats::Scalar lsqRescheduledLoads;

    /** Number of times the LSQ is blocked due to the cache. */
    Stats::Scalar lsqCacheBlocked;

  public:
    /** Executes the load at the given index. */
    template <class T>
    Fault read(Request *req, T &data, int load_idx);

    /** Executes the store at the given index. */
    template <class T>
    Fault write(Request *req, T &data, int store_idx);

    /** Returns the index of the head load instruction. */
    int getLoadHead() { return loadHead; }
    /** Returns the sequence number of the head load instruction. */
    InstSeqNum getLoadHeadSeqNum()
    {
        if (loadQueue[loadHead]) {
            return loadQueue[loadHead]->seqNum;
        } else {
            return 0;
        }

    }

    /** Returns the index of the head store instruction. */
    int getStoreHead() { return storeHead; }
    /** Returns the sequence number of the head store instruction. */
    InstSeqNum getStoreHeadSeqNum()
    {
        if (storeQueue[storeHead].inst) {
            return storeQueue[storeHead].inst->seqNum;
        } else {
            return 0;
        }

    }

    /** Returns whether or not the LSQ unit is stalled. */
    bool isStalled()  { return stalled; }
};

template <class Impl>
template <class T>
Fault
EdgeLSQUnit<Impl>::read(Request *req, T &data, int load_idx)
{
    DynInstPtr load_inst = loadQueue[load_idx];

    assert(load_inst);

    assert(!load_inst->isExecuted());

    // Check the SQ for any previous stores that might lead to forwarding

    // This will handle EDGE-like forwarding scheme that
    // forward datas both inter and intra blocks.

    int store_idx = storeHead;

    // Traverse the store queue starting from the queue head
    // to find the first unpossible forward store idx, then
    // check every possible store for forwarding in an descending
    // order from the first unpossible store to store queue head.
    while (store_idx != storeTail) {

        DynInstPtr store_candidate = storeQueue[store_idx].inst;

        // If the store inst in the same block is with a greater LSID, no
        // forward exists, break out the loop as well.
        if ((store_candidate->getBlockID() == load_inst->getBlockID()) &&
            (store_candidate->threadNumber == load_inst->threadNumber) &&
            (store_candidate->staticInst->getLSID() >
             load_inst->staticInst->getLSID())) {

            break;
        }

        // If store idx hits the younger inst block, no possible forward
        // exists, break out the loop.
        if ((store_candidate->getBlockID() > load_inst->getBlockID()) &&
            (store_candidate->threadNumber == load_inst->threadNumber)) {
            break;
        }

        // Any older inst block could have possiblly forwarded stores,
        // go on traversing.
        incrStIdx(store_idx);
    }

    // Check for the validation of store idx
    if(store_idx == storeHead) {
       // No stores in SQ satisfy the forwarding condition,
       // then set the store idx to NULL.
       store_idx = -1;
    } else {
       // There're stores in SQ may possiblly satisfying the
       // forwarding condition, then exlude the first unpossible
       // one for later traversing from this idx to SQ head.
       decrStIdx(store_idx);
    }

    int store_size = 0;

    DPRINTF(EdgeLSQUnit, "Read called by load idx %i @%#x, while looking for "
            "forwards from store idx %i in SQ.\n",
            load_idx,
            req->getPaddr(),
            store_idx);

    bool all_forward = true;
    bool partial_forward = false;

    //Check whether data can be forwarded from store for each byte
    for (int offset = 0; offset < req->getSize(); ++offset) {

        int idx = store_idx;

        // Check for forwarding through a valid idx
        while (idx != -1) {

            assert(storeQueue[idx].inst);

            assert((storeQueue[idx].inst->getBlockID()
                   < load_inst ->getBlockID())||
                   ((storeQueue[idx].inst ->getBlockID() ==
                   load_inst ->getBlockID())&&
                   (storeQueue[idx].inst ->staticInst ->getLSID() <
                   load_inst ->staticInst ->getLSID())));

            store_size = storeQueue[idx].size;

            // Check store to guarantee validation of itself.
            if (store_size == 0) {
                // Size of 0 means invalid stores
                if (idx == storeHead) { // If idx hits head of SQ, traversing end.
                    idx = -1;
                } else { // If idx still stands, go on traversing.
                    decrStIdx(idx);
                }
                continue;

            } else if (storeQueue[idx].inst->uncacheable()) {
                // @todo:
                // Uncacheable store can not forwarding as well,
                // but I don't concern about handling uncacheable
                // stores so far.
                if (idx == storeHead) {
                    idx = -1;
                } else {
                    decrStIdx(idx);
                }
                continue;
            }

            assert(storeQueue[idx].inst->effAddrValid);

            // Figure out the forwarding boudaries.
            bool store_has_lower_limit =
                (req->getVaddr() + offset) >=
                storeQueue[idx].inst->effAddr;
            bool store_has_upper_limit =
                (req->getVaddr() + offset) <
                (storeQueue[idx].inst->effAddr + store_size);

            if (store_has_lower_limit && store_has_upper_limit) {
                //This Byte can be forwarded.
                //Set the forward flag and data of this byte.
                int position = req->getVaddr()
                               + offset - storeQueue[idx].inst->effAddr;

                char data = storeQueue[idx].data[position];

                load_inst ->setForward(offset , data);

                partial_forward = true;

                break;
            }

            // This byte can not be forwarded, find next.
            if (idx == storeHead) { // Hit SQ head, stop traversing.
                idx = -1;
            }else{ // Come on!
                decrStIdx(idx);
            }

        }

        // -1 means there's a byte can not be forwarded.
        if (idx == -1) {
            all_forward = false;
        }
    }

    if (partial_forward && !all_forward) {
        lsqPartialForwLoads ++;
    }

    if (all_forward) {
        //All load data can be forwarded from stores.
        char forwardedData[Impl::MaxByteNum];
        for (int i = 0; i < req->getSize(); ++i) {
            forwardedData[i] = load_inst ->getForwardedData(i);
        }

        // Copy data to read buffer.
        memcpy(&data, forwardedData, sizeof(T));
        assert(!load_inst->memData);
        load_inst->memData = new uint8_t[64];
        memcpy(load_inst->memData, forwardedData, req->getSize());

        DPRINTF(EdgeLSQUnit, "Forwarding from store to load to "
                "addr %#x, data %#x\n",
                req->getVaddr(), data);

        PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq,
                                        Packet::Broadcast);

        data_pkt->dataStatic(load_inst->memData);

        WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);

        // We'll say this has a 1 cycle load-store forwarding latency
        // for now.
        // @todo: Need to make this a parameter.
        cpu->schedule(wb, curTick);

        ++lsqAllForwLoads;

        return NoFault;
    }

    // If there's no forwarding case, then go accessing memory
    DPRINTF(EdgeLSQUnit, "Doing memory access for inst [sn:%lli] PC %#x\n",
            load_inst->seqNum, load_inst->readPC());

    assert(!load_inst->memData);
    load_inst->memData = new uint8_t[64];

    ++usedPorts;

    // if the cache is not blocked, do cache access
    if (!lsq->cacheBlocked()) {
        PacketPtr data_pkt =
            new Packet(req,
                       (req->isLLSC() ?
                       MemCmd::LoadLockedReq : MemCmd::ReadReq),
                       Packet::Broadcast);

        data_pkt->dataStatic(load_inst->memData);

        LSQSenderState *state = new LSQSenderState;
        state->isLoad = true;
        state->idx = load_idx;
        state->inst = load_inst;
        data_pkt->senderState = state;

        if (!dcachePort->sendTiming(data_pkt)) {
            // Delete state and data packet because a load retry
            // initiates a pipeline restart; it does not retry.
            delete state;
            delete data_pkt->req;
            delete data_pkt;

            req = NULL;

            // If the access didn't succeed, tell the LSQ by setting
            // the retry thread id.
            lsq->setRetryTid(lsqID);
        }
    }

    // If the cache was blocked, or has become blocked due to the access,
    // handle it.
    if (lsq->cacheBlocked()) {
        if (req)
            delete req;

        if (load_inst->memData) {
            delete [] load_inst->memData;
            load_inst->memData = NULL;
        }

        ++lsqCacheBlocked;

        // Record that the load was blocked due to memory.  This
        // load will squash all instructions after it, be
        // refetched, and re-executed.
        isLoadBlocked = true;
        loadBlockedHandled = false;
        //blockedLoadSeqNum = load_inst->seqNum;
        blockedLoadSeqNum = load_inst->getBlockID();

        // No fault occurred, even though the interface is blocked.
        return NoFault;
    }

    return NoFault;
}

template <class Impl>
template <class T>
Fault
EdgeLSQUnit<Impl>::write(Request *req, T &data, int store_idx)
{
    assert(storeQueue[store_idx].inst);

    DPRINTF(EdgeLSQUnit, "Doing write to store idx %i, physical addr %#x"
            " virtual addr %#x data %#x"
            " | storeHead:%i [sn:%i]\n",
            store_idx, req->getPaddr(),
            req->getVaddr(),
            data,
            storeHead,
            storeQueue[store_idx].inst->seqNum);

    storeQueue[store_idx].req = req;
    storeQueue[store_idx].size = sizeof(T);
    assert(sizeof(T) <= sizeof(storeQueue[store_idx].data));

    T gData = htog(data);
    memcpy(storeQueue[store_idx].data, &gData, sizeof(T));

    // This function only writes the data to the store queue, so no fault
    // can happen here.
    return NoFault;
}

#endif // __CPU_EDGE_LSQ_UNIT_HH__
